<template>
  <div>
    <el-dialog
      title="选择商品"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :before-close="handleClose"
      :fullscreen="fullScreen"
      :class="{ 'full-screen': fullScreen }"
    >
      <div slot="title" class="title-box">
        <div>选择商品</div>
        <el-image
              :src="require('@/assets/fullscreen.png')"
              style="width: 23px; height: 23px"
              @click="onFullScreenShow()"
            ></el-image>
      </div>
      <div class="goods-info">
        <div class="goods-image" v-if="goodsInfo.goodsImg">
          <el-image :src="goodsInfo.goodsImg" fit="cover" style="width: 100%; height: 100%"></el-image>
        </div>
        <div class="goods-detail">
          <div class="goods-name">
            {{ goodsInfo.goodsName }},{{ goodsInfo.specialFunctionColorStr }},{{ goodsInfo.specialFunctionSizeStr }}
          </div>
          <div class="goods-unit">
            <span>仓库：{{ goodsInfo.storeName }}</span>
            <span style="margin-left: 20px">单位：{{ goodsInfo.goodsUnitName }}</span>
          </div>
        </div>
      </div>

      <div class="color-size-section">
        <!-- 颜色选择 -->
        <div class="color-section">
          <div class="section-title">颜色</div>
          <div class="color-list">
            <div v-for="color in colors" :key="color.colorId" class="color-item">
              <div class="color-badge" v-if="color.number > 99999999">99999999+</div>
              <div class="color-badge" v-else-if="color.number > 0">{{ color.number }}</div>
              <el-button
                :type="selectedColor === color.colorId ? 'primary' : ''"
                @click="handleColorSelect(color)"
                size="small"
                >{{ color.colorName }}</el-button
              >
            </div>
          </div>
        </div>

        <!-- 尺码表格 -->
        <div class="size-section">
          <div class="section-title">尺码</div>
          <el-table
            :data="sizeTableData"
            border
            size="small"
            style="width: 100%"
            show-summary
            :summary-method="getSummaries"
            :header-cell-style="{
              color: '#666666',
              textAlign: 'center',
              height: '30px',
              backgroundColor: '#E3E3E3',
              padding: '0',
            }"
            :cell-style="{
              textAlign: 'center',
              height: '30px',
              padding: '0',
            }"
          >
            <el-table-column prop="index" label="序号" width="60"> </el-table-column>
            <el-table-column prop="sizeName" label="属性值"> </el-table-column>
            <el-table-column prop="useNumber" label="可用库存" width="120"> </el-table-column>
            <el-table-column prop="number" label="数量" width="120">
              <template slot-scope="scope">
                <span v-if="propParams.billDisabled">{{ scope.row.number || 0 }}</span>
                <el-input
                  v-else
                  type="text"
                  v-model="scope.row.number"
                  @focus="focusSelect"
                  :min="0"
                  @input="handleInput(scope.$index, 'number', $event)"
                  @blur="handleBlur(scope.row)"
                />
                <!-- onkeyup="value=value.replace(/[^\d.]/g,'')" -->

              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <div class="total-info">已选数量：{{ totalNumber }}</div>
        <div class="buttons">
          <el-button @click="handleClose" size="small">取消</el-button>
          <el-button type="primary" @click="handleConfirm" size="small">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <PopupReminder ref="reminderRef" :tipsData="tipsData"></PopupReminder>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
import PopupReminder from './popupReminder'
import { sysConfig, accAdd, formatFour } from '@/utils/index'
import { formatNumber } from '../../utils'
export default {
  name: 'DialogGoodsSelect',
  components: {
    PopupReminder,
  },
  data() {
    return {
      dialogVisible: false,
      goodsInfo: {
        goodsImg: '',
        goodsName: '',
        goodsUnit: '',
        storeName: '',
      },
      colors: [],
      selectedColor: '',
      sizeTableData: [],
      totalNumber: 0,
      propParams: {},
      tipsData: {
        tipsState: '',
        tipsWords: '',
        tipsMark: '',
      },
      fullScreen: false,
    }
  },
  computed: {
    allowNegative() {
      return sysConfig().allow_negative_inventory
    },
  },
  methods: {
    showDialog(params) {
      this.propParams = params
      this.resetData()
      this.dialogVisible = true
      this.getGoodsInfo()
      console.log(this.propParams)
    },
    onFullScreenShow() {
      this.fullScreen = !this.fullScreen
    },
    focusSelect(e) {
      e.target.select()
    },
    handleClose() {
      this.dialogVisible = false
      this.resetData()
      this.$emit('onSpecialClose')
    },
    handleColorSelect(color) {
      this.selectedColor = color.colorId
      this.sizeTableData = color.sizeList
    },
    handleConfirm() {
      if (this.propParams.billDisabled) {
        this.handleClose()
        return
      }
      const selectedItems = this.sizeTableData.filter((item) => item.quantity > 0)
      if (this.totalNumber == 0) {
        this.$message.warning('请输入商品数量')
        return
      }
      this.$emit('updateSpecialColorSize', {
        ...this.propParams,
        list: this.colors,
        totalNumber: this.totalNumber,
      })
      this.handleClose()
    },
    resetData() {
      this.selectedColor = ''
      this.sizeTableData = []
      this.colors = []
      this.totalNumber = 0
    },
    getAttributeValue(colorId, sizeId, useNumber) {
      let list = this.propParams.specialList || []
      let result = {
        number: 0,
        id: '',
      }
      for (let index = 0; index < list.length; index++) {
        let element = list[index]
        if (element.colorId == colorId && element.sizeId == sizeId) {
          if (this.propParams.accessType == 'out' && !this.allowNegative  && !this.propParams.billDisabled) {
            result.number = Math.max(Math.min(useNumber, element.number), 0)
            result.id = element.id
            if (result.number < element.number) {              
              this.handleShowTip()
            }
          } else {
            result.number = element.number
            result.id = element.id
          }
        }
      }
      return result
    },
    getGoodsInfo() {
      let url = '/xghGoods/xghGoods/queryAttributeGoodsById'
      let params = {
        id: this.propParams.goodsId,
        storeId: this.propParams.storehouseId,
      }
      getAction(url, params).then((res) => {
        if (res.code == 200) {
          this.goodsInfo = res.result || {}
          let img = this.goodsInfo.goodsImg || ''
          this.goodsInfo.goodsImg = img.split(',')[0]
          this.colors = this.goodsInfo.attributeList || []
          for (let index = 0; index < this.colors.length; index++) {
            let element = this.colors[index]
            let sizeList = element.sizeList || []
            let sizeNum = 0
            for (let i = 0; i < sizeList.length; i++) {
              let item = sizeList[i]
              let atValue = this.getAttributeValue(element.colorId, item.sizeId, item.useNumber)
              item.useNumber = item.useNumber || 0
              item.number = atValue.number
              item.id = atValue.id || item.id
              item.index = i + 1
              sizeNum = accAdd(sizeNum, item.number)
            }
            element.number = sizeNum
            this.totalNumber = accAdd(this.totalNumber, sizeNum)
          }
          this.handleColorSelect(this.colors[0])
        }
      })
    },
    handleInput(index, prop, value) {
      // 只保留数字字符
      let validValue = value.replace(/[^0-9.]/g, '');
      // 更新表格数据
      this.$set(this.sizeTableData[index], prop, validValue == '' ? null : validValue);
    },
    handleBlur(row) {
      row.number = Number(formatNumber(row.number))
      if (this.propParams.accessType == 'out' && !this.allowNegative && row.number > row.useNumber && row.number > 0) {
        row.number = Math.max(row.useNumber, 0)
        this.handleShowTip()
      }
      this.handleUpdateColorNum()
    },
    handleUpdateColorNum() {
      let color = this.colors.find((item) => item.colorId == this.selectedColor)
      let summary = 0
      if (color) {
        let sizeList = color.sizeList || []
        for (let i = 0; i < sizeList.length; i++) {
          let item = sizeList[i]
          summary = accAdd(summary, item.number)
        }
      }
      color.number = summary
      this.$set(
        this.colors,
        this.colors.findIndex((item) => item.colorId == this.selectedColor),
        color
      )
      this.totalNumber = this.colors.reduce((sum, item) => accAdd(sum + (item.number || 0)), 0)
    },
    handleShowTip() {
      this.tipsData.tipsWords = '库存数量不足，系统不允许负库存，请确认商品出库数量。'
      this.tipsData.single = true
      this.tipsData.singleText = '关闭'
      this.$refs.reminderRef.dialogVisible = true
    },
    // 合计列计算
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      console.log(param);
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          
        } else {
          const values = data.map((item) => item[column.property])
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              if (!isNaN(curr)) {
                return accAdd(prev, curr)
              } else {
                return prev
              }
            }, 0)
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 13px 20px;
  max-height: calc(85vh - 163px);
  overflow-y: auto;
}
.full-screen ::v-deep .el-dialog__body {
  max-height: calc(100vh - 163px);
}
.title-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-image {
    cursor: pointer;
  }
  width: calc(100% - 50px);
  font-family: PingFang SC-Semibold;
}
.goods-info {
  display: flex;
  // padding: 0 20px 20px;
  padding-bottom: 13px;
  border-bottom: 1px solid #ebeef5;
  .goods-image {
    width: 64px;
    height: 64px;
    flex-shrink: 0;
    margin-right: 20px;
  }
  .goods-detail {
    
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .goods-name {
      font-size: 14px;
      margin-bottom: 6px;
      overflow: hidden;
      -webkit-line-clamp: 2;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
    }

    .goods-code,
    .goods-price,
    .goods-unit {
      font-size: 12px;
      color: #666;
      margin-bottom: 3px;
    }
  }
}

.color-size-section {
  padding-top: 20px;

  .section-title {
    font-size: 16px;
    color: #666;
    margin-bottom: 5px;
    width: 80px;
    padding-top: 2px;
    font-family: PingFang SC-Semibold;
    flex-shrink: 0;
  }

  .color-section {
    display: flex;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ebeef5;

    .color-list {
      display: flex;
      flex-wrap: wrap;

      .color-item {
        position: relative;
        margin-right: 10px;
        margin-bottom: 10px;
      }
      .color-badge {
        position: absolute;
        top: -5px;
        right: -5px;
        padding: 0 6px;
        text-align: center;
        white-space: nowrap;
        background-color: #f56c6c;
        font-size: 10px;
        color: white;
        border-radius: 7px;
        font-weight: bold;
      }
    }
  }
  .size-section {
    display: flex;
  }
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;

  .total-info {
    font-size: 16px;
  }

  .buttons {
    .el-button {
      margin-left: 10px;
    }
  }
}
::v-deep .el-table-column--selection .cell {
  padding: 0 10px;
}
::v-deep .el-table--border .el-table__cell:first-child .cell {
  padding: 0 10px;
}
::v-deep .el-table {
  border: 1px solid #ebeef5;
  .cell {
    padding: 2px;
  }
  .el-table__cell {
    padding: 5px 0;
    text-align: center;
  }
}
::v-deep .el-input {
  height: 26px;

  .el-input__inner {
    height: 26px;
    border-radius: 0;
    padding: 0 5px;
    font-size: 12px;
    line-height: 22px;
    text-align: center;
  }
  /* 隐藏上下箭头 */
  input[type='number']::-webkit-outer-spin-button,
  input[type='number']::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  input[type='number'] {
    -moz-appearance: textfield;
  }
}
</style>